from flask import render_template,redirect,url_for,session,request,jsonify
from flask_login import login_user, login_required, logout_user, current_user

from service.project import ProjectService, ProjectForm
from controller import app
import json

@app.route('/manage_projects')
@app.route('/manage_projects', methods=['GET','POST'])
def manage_projects():
    '''When a user logs in, their session is marked as 'fresh'.
    '''
    project_service = ProjectService()
    _projects = project_service.get_projects()
    if _projects == []:
        return render_template('projects.html', projects=[], project_errors=[])
    else:
        return render_template('projects.html', projects=json.dumps(_projects), project_errors=[])


@app.route('/display_projects')
@login_required
def display_projects():
    _serv = ProjectService()
    _projects = _serv.get_projects()
    if session['project_errors'] == '':
        return render_template('projects.html', projects=json.dumps(_projects), project_errors=[])
    else:
        errors = session['project_errors']
        return jsonify(project_errors=json.dumps(errors))



"""
@app.route('/submit_project', methods=['GET','POST'])
#@login_required
def submit_project():
    form = ProjectForm()
    if form.is_submitted():
        if form.has_error():
            session['project_errors'] = json.dumps(form.errors)
            return redirect(url_for('display_projects'))#errors_json=json.dumps(form.errors)))
        else:
            session['project_errors'] = []
            service = ProjectService()
            service.submit_project(form.inputs)
            return redirect(url_for('manage_projects')) 
"""

""" The following are Ajax handlers
"""
@app.route('/submit_project', methods=['GET','POST'])
@login_required
def submit_project():
    form = ProjectForm()
    if form.is_submitted():
        if form.has_error():
            return jsonify(errors=json.dumps(form.errors))
        else:
            service = ProjectService()
            service.submit_project(form.input, form.mode)
            return jsonify(errors=[])



@app.route('/get_project')
@app.route('/get_project', methods=['GET','POST'])
@login_required
def get_project():
    sid = request.values['sid']
    serv = ProjectService()
    project = serv.get_project(sid)
    return jsonify(project=json.dumps(project))

@app.route('/delete_projects')
@app.route('/delete_projects', methods=['GET','POST'])
def delete_projects():
    sid = request.values['sid']
    serv = ProjectService()
    serv.delete_project(sid)
    _projects = serv.get_projects()
    
    return jsonify(projects=json.dumps(_projects))


@app.route('/get_project_tree')
@app.route('/get_project_tree', methods=['GET','POST'])
@login_required
def get_project_tree():
    serv = ProjectService()
    tree_datas = serv.get_project_tree()

    return jsonify(trees=json.dumps(tree_datas))
  